﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using forever.Gobal;

namespace gencode.UI
{
    public partial class ucGenerateProject : UserControl
    {
        private string database;
        private List<string> sMethodNames = new List<string>();
        //1: select; 2: update; 3: delete; 4: insert; 5:page;
        private List<string> sMethodType = new List<string>();
        private List<string> sMethodDescription = new List<string>();
        private List<string> sWhereType = new List<string>();
        private List<DataTable> sFieldDisplays = new List<DataTable>();
        private List<DataTable> sFieldConditions = new List<DataTable>();
        private DataTable dt;
        private DataTable dtUnique;
        private DataTable dtPK;
        private DataTable dtFK;
        private DataTable dtNotIdentitys;
        private DataTable dtDefault;
        public ucGenerateProject(string database)
        {
            InitializeComponent();
            this.database = database;
            init();
        }
        void init()
        {
            txtBLL.Text = ConfigurationSettings.AppSettings["modifiersBLL"];
            txtDAL.Text = ConfigurationSettings.AppSettings["modifiersDAL"];
            txtDTO.Text = ConfigurationSettings.AppSettings["modifiersDTO"];
            txtView.Text = ConfigurationSettings.AppSettings["modifiersView"];
            txtBusinessLogicLayer.Text = ConfigurationSettings.AppSettings["BusinessLogicLayer"];
            txtDataAccessLayer.Text = ConfigurationSettings.AppSettings["DataAccessLayer"];
            txtPresentationLayer.Text = ConfigurationSettings.AppSettings["PresentationLayer"];
            txtDataObjectLayer.Text = ConfigurationSettings.AppSettings["DataObjectLayer"];
            txtUserClass.Text = ConfigurationSettings.AppSettings["user"];
            txtSproc.Text = ConfigurationSettings.AppSettings["modifierSproc"];
            txtDescriptionClass.Text = "";
            txtNamespaceParent.Text = database;

            chkInfoClass.Checked = true;
            //
        }
        void generateDefault(string table)
        {
            string name;
            dt = Gobal.SelectColumnNames(database, table);
            dtDefault = Gobal.SelectColumnNamesNotRows(database, table);
            dtFK = Gobal.SelectColumnsByConstraintType(database, table, "FOREIGN KEY");
            dtPK = Gobal.SelectColumnsByConstraintType(database, table, "PRIMARY KEY");
            dtUnique = Gobal.SelectColumnsByConstraintType(database, table, "UNIQUE");
            dtNotIdentitys = Gobal.SelectColumnByNotColumnIdentitys(database, table);
            // ----------------- clear 
            sMethodDescription.Clear();
            sMethodNames.Clear();
            sWhereType.Clear();
            sFieldDisplays.Clear();
            sFieldConditions.Clear();
            sMethodType.Clear();
            //---------------------------------------------------------------------
            //select all
            dtDefault.Rows.Clear();
            DataTable dt1 = dtDefault.Clone();
            sMethodDescription.Add("Lấy ra tất cả các trường và các bản ghi");//pulled out all the fields and records 
            sMethodNames.Add("SelectAll");
            sWhereType.Add("");
            sFieldDisplays.Add(dt);
            sFieldConditions.Add(dt1);
            sMethodType.Add("Select");
            // select list by fk
            for (int i = 0; i < dtFK.Rows.Count; i++)
            {
                DataTable dt2 = dtDefault.Clone();
                dt2.ImportRow(dtFK.Rows[i]);
                sMethodNames.Add("SelectListBy" + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                sMethodDescription.Add("Lấy ra danh sách các bản ghi theo khóa ngoại " + dtFK.Rows[i]["COLUMN_NAME"]);
                sWhereType.Add("");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dt2);
                sMethodType.Add("Select");
            }
            // select only by pk by and
            if (dtPK.Rows.Count > 0)
            {
                sMethodNames.Add("SelectOnlyBy" + getPK());
                sMethodDescription.Add("Lấy ra một bản ghi theo primary key");
                sWhereType.Add("and");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dtPK);
                sMethodType.Add("Select");
            }
            // select only by unique
            for (int i = 0; i < dtUnique.Rows.Count; i++)
            {
                name = "SelectOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() +
                      dtUnique.Rows[0]["COLUMN_NAME"].ToString().Substring(1);
                if (!isWhere(sMethodNames, name))
                {
                    DataTable dt22 = dtDefault.Clone();
                    dt22.ImportRow(dtUnique.Rows[i]);
                    sMethodNames.Add("SelectOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                    sMethodDescription.Add("Lấy ra một bản ghi theo unique " + dtUnique.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dt);
                    sFieldConditions.Add(dt22);
                    sMethodType.Add("Select");
                }
            }
            //end
            //---------------------------------------------------------------------
            //update only by pk
            if (dtPK.Rows.Count > 0)
            {
                sMethodDescription.Add("Cập nhập một bản ghi dữ liệu");
                sMethodNames.Add("UpdateOnlyBy" + getPK());
                sWhereType.Add("and");
                sFieldDisplays.Add(dtNotIdentitys);
                sFieldConditions.Add(dtPK);
                sMethodType.Add("Update");
            }
            // update only by unique
            for (int i = 0; i < dtUnique.Rows.Count; i++)
            {
                name = "UpdateOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() +
                      dtUnique.Rows[0]["COLUMN_NAME"].ToString().Substring(1);
                if (!isWhere(sMethodNames, name))
                {
                    DataTable dt31 = dtDefault.Clone();
                    dt31.ImportRow(dtUnique.Rows[i]);
                    sMethodNames.Add(name);
                    sMethodDescription.Add("Cập nhập một bản ghi theo unique " + dtUnique.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dtNotIdentitys);
                    sFieldConditions.Add(dt31);
                    sMethodType.Add("Update");
                }
            }
            //end
            //---------------------------------------------------------------------
            //delete all
            //sMethodDescription.Add("Xóa tất cả các bản ghi");
            //sMethodNames.Add("DeleteAll");
            //sWhereType.Add("");
            //sFieldDisplays.Add(dt);
            //sFieldConditions.Add(dtDefault);
            //sMethodType.Add("Delete");
            // delete only by pk by and
            if (dtPK.Rows.Count > 0)
            {
                sMethodNames.Add("DeleteOnlyBy" + getPK());
                sMethodDescription.Add("Xóa một bản ghi theo primary key");
                sWhereType.Add("and");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dtPK);
                sMethodType.Add("Delete");
            }
            // delete list by fk
            for (int i = 0; i < dtFK.Rows.Count; i++)
            {
                DataTable dt41 = dtDefault.Clone();
                dt41.ImportRow(dtFK.Rows[i]);
                sMethodNames.Add("DeleteListBy" + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                sMethodDescription.Add("Xóa danh sách các bản ghi theo khóa ngoại " + dtFK.Rows[i]["COLUMN_NAME"]);
                sWhereType.Add("");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dt41);
                sMethodType.Add("Delete");
            }

            // delete only by unique
            for (int i = 0; i < dtUnique.Rows.Count; i++)
            {
                name = "DeleteOnlyBy" + dtUnique.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() +
                      dtUnique.Rows[0]["COLUMN_NAME"].ToString().Substring(1);
                if (!isWhere(sMethodNames, name))
                {
                    DataTable dt4 = dtDefault.Clone();
                    dt4.ImportRow(dtUnique.Rows[i]);
                    sMethodNames.Add(name);
                    sMethodDescription.Add("Xóa một bản ghi theo unique " + dtUnique.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dt);
                    sFieldConditions.Add(dt4);
                    sMethodType.Add("Delete");
                }
            }
            //---------------------------------------------------------------------
            //insert all

            sMethodDescription.Add("Thêm dữ liệu vào tất cả các trường và các bản ghi");
            sMethodNames.Add("Insert");
            sWhereType.Add("");
            sFieldDisplays.Add(dtNotIdentitys);
            sFieldConditions.Add(dtDefault);
            sMethodType.Add("Insert");
            //---------------------------------------------------------------------
            //page all

            if (cbbGenerateOption.SelectedIndex == 0)
            {
                sMethodDescription.Add("Phân trang lấy tất cả các trường và các bản ghi");//pulled out all the fields and records 
                sMethodNames.Add("PagesAll");
                sWhereType.Add("");
                sFieldDisplays.Add(dt);
                sFieldConditions.Add(dtDefault);
                sMethodType.Add("Page");
                //page list by fk
                for (int i = 0; i < dtFK.Rows.Count; i++)
                {
                    DataTable dt5 = dtDefault.Clone();
                    dt5.ImportRow(dtFK.Rows[i]);
                    sMethodNames.Add("PagesListBy" + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtFK.Rows[i]["COLUMN_NAME"].ToString().Substring(1));
                    sMethodDescription.Add("Phân trang lấy ra danh sách các bản ghi theo khóa ngoại " + dtFK.Rows[i]["COLUMN_NAME"]);
                    sWhereType.Add("");
                    sFieldDisplays.Add(dt);
                    sFieldConditions.Add(dt5);
                    sMethodType.Add("Page");
                }
            }
        }
        public bool isWhere(List<string> list, string search)
        {
            IEnumerable<string> query = list.Where(item => item.Equals(search));
            foreach (string VARIABLE in query)
            {
                return true;
            }
            return false;
        }
        string getPK()
        {
            string str = "";
            if (dtPK.Rows.Count > 0)
            {
                for (int i = 0; i < dtPK.Rows.Count - 1; i++)
                {
                    str += dtPK.Rows[i]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtPK.Rows[i]["COLUMN_NAME"].ToString().Substring(1)
                    + "And";
                } str += dtPK.Rows[dtPK.Rows.Count - 1]["COLUMN_NAME"].ToString().Substring(0, 1).ToUpper() + dtPK.Rows[dtPK.Rows.Count - 1]["COLUMN_NAME"].ToString().Substring(1)
                     ;
            }
            return str;
        }
        List<string> GenText(string table)
        {
            List<string> rs = new List<string>();
            switch (cbbLanguages.SelectedItem.ToString())
            {
                case "C# Three layer":
                    gencodeSharp gen = new gencodeSharp(chkInfoClass.Checked, dtPK,
                                                        txtSproc.Text, comboBoxEdit1.Text, table, txtUserClass.Text,
                                                        txtDescriptionClass.Text, txtView.Text, txtDTO.Text,
                                                        txtBLL.Text,
                                                        txtDAL.Text, txtDataAccessLayer.Text,
                                                        txtDataObjectLayer.Text,
                                                        txtBusinessLogicLayer.Text, txtPresentationLayer.Text,
                                                        txtNamespaceParent.Text, sMethodType, sWhereType,
                                                        sMethodDescription, sMethodNames, dt,
                                                        sFieldDisplays, sFieldConditions,
                                                        cbbCnData.Text);
                    rs.Add(gen.GenerateClassView());
                    rs.Add(gen.GenerateClassBLL());
                    rs.Add(gen.GenerateClassDTO());
                    rs.Add(gen.GenerateClassDAL());
                    rs.Add(gen.GenerateSprocs());
                    return rs;
            }
            return rs;
        }
        private void bntChangeDefault_Click(object sender, EventArgs e)
        {
            init();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            DataTable tables = Gobal.SelectTableNames(database);
            int total = tables.Rows.Count;
            string table = "";
            string date = "";
            string paths = "";
            string path = "";
            try
            {
                if (total > 0)
                {
                    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
                    folderBrowserDialog1.Description = "Chose folder save list files of Database " + database;
                    // folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
                    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                    {
                        date = string.Format("{0:hhmmss_ddMMyyyy}", DateTime.Now);
                        paths = folderBrowserDialog1.SelectedPath + "\\" + database + "_" + date;
                        path = ""; List<string> rs = new List<string>();
                        if (!Directory.Exists(paths))
                        {
                            Directory.CreateDirectory(paths);
                        }
                        for (int i = 0; i < total; i++)
                        {
                            table = tables.Rows[i]["TABLE_NAME"].ToString();
                            if (table.Equals("XEPLOAI"))
                            {
                                String A = "";
                            }
                            generateDefault(table);
                            rs = GenText(table);
                            if (rs.Count > 0)
                            {
                                path = paths + "\\" + table;
                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                }
                                Gobal.writeFile(path + "\\" + table + txtBLL.Text + ".cs", rs[1]);
                                Gobal.writeFile(path + "\\" + table + txtDAL.Text + ".cs", rs[3]);
                                Gobal.writeFile(path + "\\" + table + txtDTO.Text + ".cs", rs[2]);
                                Gobal.writeFile(path + "\\" + table + txtView.Text + ".txt", rs[0]);
                                Gobal.writeFile(path + "\\" + txtSproc.Text + table + ".sql", rs[4]);
                            }
                        }
                        MessageBox.Show("Create list files completed successfully", "Message", MessageBoxButtons.OK,
                                     MessageBoxIcon.Information);
                    }
                    
                }
            }
            catch (Exception ex)
            {
                if (Directory.Exists(paths))
                {
                    Directory.Delete(paths, true);
                }
                MessageBox.Show(ex.Message + "-" + table, "Message", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
            }
            
        }
    }
}
